<template>
    <a-checkbox-group v-model:value="InputValue" :options="Dict" :disabled="readonly" />
</template>
<script setup>
import { ref, watch, watchEffect, inject } from 'vue';
import { FormatIsbyteSelectValue, FormatIsbyteFormValue, FormatDictWithOption } from '../util/index'


const emit = defineEmits(['UpdateEvent'])
const props = defineProps({
    option: Object,
    Value: {},
});

const InputValue = ref([]);

const readonly = ref(false);
const GetDict = inject('GetDict')
const Dict = ref([]);
const SelectValue = ref([])

if (Array.isArray(props.option.Dict)) {
    Dict.value = FormatDictWithOption(props.option.Dict, props.option.DictOption);
} else {
    const DictKey = props.option.Dict.split(':');
    if (DictKey.length == 1) {
        GetDict(DictKey[0]).then(res => {
            Dict.value = FormatDictWithOption(res, props.option.DictOption);
            SelectValue.value = FormatIsbyteSelectValue(props.Value[props.option.key], Dict.value)
        })
    }
}

watchEffect(() => {
    readonly.value = !!props.option.readonly
})

watch(() => props.Value[props.option.key], val => {
    if (props.option.isbyte) {
        InputValue.value = FormatIsbyteSelectValue(val, Dict.value)
    } else {
        InputValue.value = val
    }
}, { immediate: true });

watch(InputValue, (val) => {
    if (props.option.isbyte) {
        emit('UpdateEvent', props.option.key, FormatIsbyteFormValue(val));
    } else {
        emit('UpdateEvent', props.option.key, val);
    }
})
</script>
<style lang="less" scoped></style>